<template>
  <div class="address-edit-box">
    <nav-bar class="nav-bar">
      <template v-slot:default>
        {{ title }}
      </template>
    </nav-bar>

    <van-address-edit
      class="edit"
      :area-list="areaList"
      :address-info="addressInfo"
      :show-delete="type == 'edit'"
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import { reactive, onMounted, toRefs, computed } from "vue";
import { Toast, Dialog } from "vant";
import { addAddress, editAddress, deleteAddress, getAddressDetail, } from "@/network/address";
import { tdist } from "../../utils/address.js";
import { useRoute, useRouter } from "vue-router";

export default {
  name: 'AddressEdit', 
  components: {NavBar},
  setup() {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      areaList: {
        province_list: {}, // 省
        city_list: {},     // 市
        county_list: {},   // 县
      },
      searchResult: [],
      addressInfo: {},
      type: "add",
      addressId: "",
      title: "",
    })

    

    onMounted( async () => {
      // 将 省 市 区/县 构造出来
      let _province_list = {}
      let _city_list = {}
      let _county_list = {}

      tdist.getLev1().forEach(p => {
        _province_list[p.id] = p.text
        tdist.getLev2(p.id).forEach(c => {
          _city_list[c.id] = c.text
          tdist.getLev3(c.id).forEach(q => {
            _county_list[q.id] =  q.text
          })
        })
      })

      state.areaList.province_list = _province_list
      state.areaList.city_list = _city_list
      state.areaList.county_list = _county_list

      const { type, addressId } = route.query

      state.type = type
      state.addressId = addressId

      if (type === 'edit') {
        const data = await getAddressDetail(addressId)

        let _areaCode = ''
        const province = tdist.getLev1()
        Object.entries(state.areaList.county_list).forEach(([id, text]) => {
        // 先找出当前对应的区
          if (text == data.county) {
            // 找到区对应的几个省份
            const provinceIndex = province.findIndex(item => item.id.substr(0, 2) == id.substr(0, 2))
            // 找到区对应的几个市区
            // eslint-disable-next-line no-unused-vars
            const cityItem = Object.entries(state.areaList.city_list).filter(([cityId, city]) => cityId.substr(0, 4) == id.substr(0, 4))[0]
            // 对比找到的省份和接口返回的省份是否相等，因为有一些区会重名
            if (province[provinceIndex].text == data.province && cityItem[1] == data.city) {
              _areaCode = id
            }
          }
        })

        state.addressInfo = {
          name: data.name,
          tel: data.phone,
          province: data.province,
          city: data.city,
          county: data.county,
          areaCode: _areaCode,
          addressDetail: data.address,
          isDefault: !!data.is_default
        }
      }
    })

    const title = computed(()=>{
      return state.type === 'add' ? '新增地址' : '编辑地址'
    })

    const onSave = async (content) => {
      const params = {
        name: content.name,
        phone: content.tel,
        province: content.province,
        city: content.city,
        county: content.county,
        address: content.addressDetail,
        is_default: content.isDefault ? 1 : 0
      }

      if (state.type === 'edit') {
        // 调用接口编辑地址
        editAddress(state.addressId, params)

      } else if (state.type === 'add') {
        // 调用接口，添加数据
        const data = await addAddress(params)
      }

      Toast('保存成功')
      setTimeout(()=>{
        router.back()
      }, 1000)
    }

    // 调用接口删除数据
    const onDelete = async () =>{
      const confirm = await Dialog.confirm({
        message:
          '确定删除吗？',
      })
      if (confirm === 'confirm') {
        const data = await deleteAddress(state.addressId)
        if (data.status !== 204) return Toast.fail('删除失败')
        // console.log(data);
        Toast('删除成功')
        setTimeout(()=>{
          router.back()
        }, 1000)
      }
      
    }

    return {
      ...toRefs(state),
      onSave,
      onDelete,
      title
    }
  }
}


</script>

<style lang="scss" scoped>
.address-box .address-item .van-button {
  background: #ee0a24 !important; 
  border-color: #ee0a24 !important; 
}
.address-edit-box .van-address-edit .van-button--danger {
  background: #ee0a24 !important;
  border: none;
}
.edit {
  .van-field__body {
    textarea {
      height: 26px !important;
    }
  }
}
.address-edit-box {
  margin-top: 44px;
  .van-address-edit {
    .van-button--danger {
      background: var(--color-tint);
      border-color: var(--color-tint);
    }
    .van-switch--on {
      background: var(--color-tint);
    }
  }
}
</style>